package com.app.oral.config

import com.app.oral.model.ExerciseMode
import org.apache.ibatis.type.BaseTypeHandler
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.MappedTypes
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException

/**
 * 练习模式自定义TypeHandler
 * 处理数据库字符串与ExerciseMode枚举之间的映射
 */
@MappedTypes(ExerciseMode::class)
class ExerciseModeTypeHandler : BaseTypeHandler<ExerciseMode>() {

    @Throws(SQLException::class)
    override fun setNonNullParameter(ps: PreparedStatement, i: Int, parameter: ExerciseMode, jdbcType: JdbcType?) {
        ps.setString(i, parameter.value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnName: String): ExerciseMode? {
        val value = rs.getString(columnName)
        return mapStringToExerciseMode(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(rs: ResultSet, columnIndex: Int): ExerciseMode? {
        val value = rs.getString(columnIndex)
        return mapStringToExerciseMode(value)
    }

    @Throws(SQLException::class)
    override fun getNullableResult(cs: CallableStatement, columnIndex: Int): ExerciseMode? {
        val value = cs.getString(columnIndex)
        return mapStringToExerciseMode(value)
    }

    /**
     * 将数据库字符串值映射到ExerciseMode枚举
     */
    private fun mapStringToExerciseMode(value: String?): ExerciseMode? {
        if (value == null) return null
        
        return when (value.lowercase()) {
            "practice" -> ExerciseMode.PRACTICE
            "test" -> ExerciseMode.TEST
            else -> {
                // 尝试按枚举名称匹配
                try {
                    ExerciseMode.valueOf(value.uppercase())
                } catch (e: IllegalArgumentException) {
                    // 默认为练习模式
                    ExerciseMode.PRACTICE
                }
            }
        }
    }
}